<?php


namespace app\common\middleware;


use app\common\enum\MainEnum;
use app\common\exception\ForbiddenException;
use app\common\model\UserPlatformModel;
use app\common\model\UserPlatformTokenModel;
use think\Request;

/**
 * token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class AuthToken
{
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        //检测token是否有效
        $accessToken = trim(ltrim(request()->header('authorization', ''), 'Bearer'));
        if (!$accessToken) {
            throw new ForbiddenException([
                'msg'  => '请输入令牌',
                'code' => MainEnum::ERROR_TOKEN_NEED,
            ]);
        }
        $where                  = [
            [
                'access_token',
                '=',
                $accessToken,
            ],
        ];
        $userPlatformTokenModel = (new UserPlatformTokenModel())->getUserPlatformToken($where);
        if (!$userPlatformTokenModel || !$userPlatformTokenModel->userInfo) {
            throw new ForbiddenException([
                'msg'  => '令牌有误',
                'code' => MainEnum::ERROR_TOKEN_ERROR,
            ]);
        }
        if (strtotime($userPlatformTokenModel->getData('expire_time')) - NOW_TIME < 0) {
            throw new ForbiddenException([
                'msg'  => '令牌已过期',
                'code' => MainEnum::ERROR_TOKEN_EXPIRE,
            ]);
        }

        if ($userPlatformTokenModel->getData('platform_specific') !== 'Admin') {
            $userId            = $userPlatformTokenModel->getData('user_id');
            $platformSpecific  = $userPlatformTokenModel->getData('platform_specific');
            $userPlatformModel = (new UserPlatformModel())->where('user_id', $userId)
                ->where('platform_specific', $platformSpecific)
                ->with([])
                ->find();
            if (!$userPlatformModel) {
                throw new ForbiddenException([
                    'msg'  => '用户不存在',
                    'code' => MainEnum::ERROR_TOKEN_ERROR,
                ]);
            }
            $request->userPlatformModel = $userPlatformModel;
        }
        else {
            $request->userPlatformModel = false;
        }
        #给token续时
        $userPlatformTokenModel->expire_time = NOW_TIME + MainEnum::APP_TOKEN_EXPIRE_TIMESTAMP;
        $userPlatformTokenModel->save();
        $request->userModel              = $userPlatformTokenModel->userInfo;
        $request->userPlatformTokenModel = $userPlatformTokenModel;
        return $next($request);
    }
}